<?php
namespace app\forum\model;
use app\base\model\BaseModel;
/**
 * 文件操作
 */
class FileModel extends BaseModel {
    //完成
    protected $_auto = array (
        array('time','time',3,'function'),
        array('user_id',USER_ID,3,'string'),
     );

    /**
     * 获取列表
     * @return array 列表
     */
    public function loadList($where = array(),$limit = 10 ,$order='file_id desc'){
        return $this->table("file as A")
                    ->join('{pre}user as B ON A.user_id = B.user_id','left')
                    ->join('{pre}thread as C ON A.thread_id = C.thread_id','left')
                    ->join('{pre}plate as D ON C.plate_id = D.plate_id','left')
                    ->field('A.*,B.username,C.title as thread_title,D.app')
                    ->where($where)
                    ->order($order)
                    ->limit($limit)
                    ->select();
    }

    /**
     * 获取数量
     * @return array 列表
     */
    public function countList($where = array()){
        return $this->table("file as A")
                    ->join('{pre}user as B ON A.user_id = B.user_id','left')
                    ->join('{pre}thread as C ON A.thread_id = C.thread_id','left')
                    ->join('{pre}plate as D ON C.plate_id = D.plate_id','left')
                    ->field('A.*,B.username,C.title as thread_title,D.app')
                    ->where($where)
                    ->count();
    }

    /**
     * 获取信息
     * @param int $fileId ID
     * @return array 信息
     */
    public function getInfo($fileId)
    {
        $map = array();
        $map['file_id'] = $fileId;
        return $this->getWhereInfo($map);
    }

    /**
     * 获取信息
     * @param array $where 条件
     * @return array 信息
     */
    public function getWhereInfo($where)
    {
        return $this->where($where)->find();
    }

    /**
     * 上传数据
     * @return array 文件信息
     */
    public function uploadData()
    {
        $upload = target('base/Upload');
        $config = array();
        $config['DIR_NAME'] = 'attachment/' . date('Y-m-d');
        $data = $upload->upload($config);
        if(!$data){
            $this->error = $upload->getErrorMsg();
            return false;
        }
        $this->add($data);
        return $data;
    }

    /**
     * 删除信息
     * @param int $fileId ID
     * @return bool 删除状态
     */
    public function delData($fileId)
    {
        $map = array();
        $map['file_id'] = $fileId;
        $info = $this->getInfo($fileId);
        if(empty($info)){
            $this->error = '未发现该文件';
            return false;
        }
        $status = $this->where($map)->delete();
        if($status){
            $file = $info['url'];
            $file = str_replace(ROOT_URL, '', $file);
            $file = realpath(ROOT_PATH . $file);
            @unlink($file);
        }
        return $status;
    }

}
